package com.chinasoftinc.facommon.view.device.abilitypersent;

import ohos.aafwk.ability.IAbilityConnection;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.bundle.ElementName;
import ohos.event.commonevent.CommonEventData;
import ohos.event.commonevent.CommonEventManager;
import ohos.event.commonevent.CommonEventSubscribeInfo;
import ohos.event.commonevent.CommonEventSubscriber;
import ohos.event.commonevent.MatchingSkills;
import ohos.global.configuration.Configuration;
import ohos.rpc.IRemoteObject;
import ohos.rpc.RemoteException;
import ohos.utils.zson.ZSONObject;

import com.chinasoftinc.facommon.DeviceControlConstants;
import com.chinasoftinc.facommon.FAConfigMgr;
import com.chinasoftinc.facommon.HilinkRegister;
import com.chinasoftinc.facommon.control.service.HilinkDeviceServiceAbility;
import com.chinasoftinc.facommon.utils.RemoteUtils;
import com.chinasoftinc.facommon.view.device.ControlDeviceAbility;
import com.chinasoftinc.facommon.utils.LogUtil;

/**
 * @since 2022-05-10
 */
public class DeviceAbilityPresent {
    protected final String TAG = getClass().getSimpleName();
    protected final AbilityConnection connection = new AbilityConnection();
    protected String deviceId = null;
    protected IRemoteObject conversationRemoteObj = null;
    protected FaEventSubscriber subscriber;
    protected ControlDeviceAbility ability;


    public DeviceAbilityPresent(ControlDeviceAbility ability) {
        this.ability = ability;
    }

    public void onStart(Intent intent) {
        this.deviceId = intent.getStringParam("deviceId");
        int systemColorMode = ability.getResourceManager().getConfiguration().getSystemColorMode();
        intent.setParam("isLight", systemColorMode == Configuration.LIGHT_MODE);
        LogUtil.info(TAG, "systemColorMode : " + systemColorMode);
        ability.setPageParams(null, intent.getParams());
        updateInfo(intent);
        subscribeFaEvent();
    }

    public void onNewIntent(Intent intent) {
        LogUtil.info(TAG, "onNewIntent params:" + ZSONObject.toZSONString(intent.getParams()));
        this.deviceId = intent.getStringParam("deviceId");
        updateInfo(intent);
    }

    public void onStop() {
        ability.disconnectAbility(connection);
        if (subscriber != null) {
            try {
                CommonEventManager.unsubscribeCommonEvent(subscriber);
            } catch (RemoteException e) {
                LogUtil.error(TAG, "unsubscribeCommonEvent error");
            }
        }
    }

    private void updateInfo(Intent intent) {
        if (conversationRemoteObj != null) {
            sendDataUpdateDeviceIdAction();
        } else {
            Intent intentS = new Intent();
            Operation operation = new Intent.OperationBuilder()
                .withBundleName(FAConfigMgr.get().getBundleName())
                .withAbilityName(HilinkDeviceServiceAbility.class.getName())
                .build();
            intentS.setOperation(operation);
            ability.connectAbility(intentS, connection);
        }
        String pid = intent.getStringParam("pid");
        String uuid = intent.getStringParam("uuid");
        HilinkRegister.get().configInfo(pid, uuid, deviceId);
    }

    /**
     * 设备控制全屏界面
     *
     * @since 2022-01-25
     */
    class AbilityConnection implements IAbilityConnection {
        @Override
        public void onAbilityConnectDone(ElementName elementName, IRemoteObject remoteObject, int i) {
            conversationRemoteObj = remoteObject;
            sendDataUpdateDeviceIdAction();
        }

        @Override
        public void onAbilityDisconnectDone(ElementName elementName, int i) {
            conversationRemoteObj = null;
        }
    }

    private void sendDataUpdateDeviceIdAction() {
        RemoteUtils.sendRemoveMessage(
            conversationRemoteObj,
            DeviceControlConstants.ACTION_MESSAGE_CODE_NOTIFY_DEVICE_ID,
            DeviceControlConstants.DEVICE_ID,
            deviceId,
            DeviceControlConstants.UPDATE_DEVICEID_DELAY
        );
    }

    private void subscribeFaEvent() {
        MatchingSkills matchingSkills = new MatchingSkills();
        addSubscribeFaEvent(matchingSkills);
        CommonEventSubscribeInfo subscribeInfo = new CommonEventSubscribeInfo(matchingSkills);
        subscriber = new FaEventSubscriber(subscribeInfo);
        try {
            CommonEventManager.subscribeCommonEvent(subscriber);
        } catch (RemoteException e) {
            LogUtil.error(TAG, "subscribeFaCloseEvent error");
        }
    }

    protected void addSubscribeFaEvent(MatchingSkills matchingSkills) {
    }

    protected void onReceiveEvent(String action, CommonEventData commonEventData) {
    }

    private class FaEventSubscriber extends CommonEventSubscriber {
        FaEventSubscriber(CommonEventSubscribeInfo subscribeInfo) {
            super(subscribeInfo);
        }

        @Override
        public void onReceiveEvent(CommonEventData commonEventData) {
            Intent intent = commonEventData.getIntent();
            String action = intent.getAction();
            LogUtil.info(TAG, "onReceiveEvent, action: " + action);
            if (action == null) {
                return;
            }
            DeviceAbilityPresent.this.onReceiveEvent(action, commonEventData);
        }
    }
}
